<?php
namespace application\datatypes;
class Time extends DataType {
	public static $name = 'Time';
	public static $fields = array(array('columnType'=>'TIME'));
	
	public static $displayParams = array(
		array(
			'label'=>'Format',
			'name'=>'format',
			'type'=>'text',
			'defaultValue'=>'g:ia'
		)
	);
	
	public static function validate($field, $data, $results) {
		if($field->cf_required && !$data[$field->cf_column]) {
			$results['errors'][] = $field->cf_display_name.' is required.';
		}
		elseif($_REQUEST[$field->cf_column]) {
			$date = strtotime($data[$field->cf_column]);
			if(!$date) $results['errors'][] = $field->cf_display_name.' must be a valid time.';
			else $results['db_fields'][$field->cf_column] = date('H:i:s', $date);
		}
		
		return $results;
	}
	
	public static function display($formElements) {
		?>
		
		<fieldset class="single-field">
			<header><?=$formElements['display']?></header>
			<section class="inner">
			<?php if($description = $formElements['description']) : ?>
				<p class="form-description"><?=$description?></p>
			<?php endif;?>
			<?=$formElements['elements']['element']?>
			</section>
		</fieldset>
		<?php
	}
	
	public static function prepareData($field, $data, $params) {
		if(!$params['format']) $params['format'] = 'g:ia';
		$time = $data[$field->cf_column];
		
		return date($params['format'], strtotime($time));
	}
	
	public static function build($field, $data) {
		$value = (strtotime($data[$field->cf_column]) > 0) ? date('h:iA', strtotime($data[$field->cf_column])) : '';

		$formElements = array('description'=>$field->cf_description, 'column'=>$column, 'display'=>$field->cf_display_name, 'data_type'=>$field->cf_data_type, 'elements'=>array(
				'element'=>
					sprintf('<input type="text" value="%1$s" name="%2$s" id="%2$s" class="timepicker"/>', $value, $column)
				
				));
		return $formElements;
	
	}
	
}
?>